<template>
	<view :class="currentTheme">
		<a-nabbar :name="title" />
		<view class="u-padding-32">
			<view class="u-margin-bottom-40">
				<view class="u-margin-bottom-40 u-text-center text-order-time u-font-28">设置门店信息，轻松组局发车</view>
				<view class="u-flex u-row-between u-margin-bottom-26">
					<text class="box-title u-font-32">上传图片</text>
					<text class="u-font-28 text-tips">最多可上传6张</text>
				</view>
				<uploader ref="image" :max-count="6" :bgColor="currentThemeObj.backgroundSecondColor"
					:list="form.sliderImage" @getImgStr="getImgStr" @uploaded="getUpload" v-if="uploadShow"></uploader>

			</view>
			<item-box paddinglr="40">
				<label-box label="门店名" labelWidth="130">
					<u-input v-model="form.name" :clearable="false" border
						:borderColor="currentThemeObj.inputBorderColor" placeholder="请输入门店名"
						:placeholder-style="`color:${currentThemeObj.placeholderColor}`" />
				</label-box>
				<label-box label="所在城市" labelWidth="130">
					<!-- <view class="u-flex">
						<view class="u-flex-1">
							<select-item v-model="form.cityAddress" :list="cityList" mode="popSelectCity"
								@getSelect="getSelectCity"></select-item>
						</view>
						<view class="addList" @click="chooseAddress">
							<u-icon size="30" name="map-fill" :color="currentThemeObj.primary"></u-icon>
						</view>
					</view> -->
					<view class="u-flex-1 u-flex diy-input-box u-row-between"  @click="chooseAddress">
						<view class="u-flex u-flex-1">
							<view style="overflow: hidden;width: 0;" v-if="form.cityAddress" class="u-line-1 u-flex-1">{{form.cityAddress}}</view>
							<view class="u-font-30" v-else :style="{color:currentThemeObj.placeholderColor}">
								省市区县、乡镇等
							</view>
						</view>
						<view class="icon-view">
							<u-icon size="30" name="map-fill" color="#765CFE"></u-icon>
						</view>
					</view>
				</label-box>
				<label-box label="详细地址" labelWidth="130">
					<u-input v-model="form.address" :clearable="false" border
						:borderColor="currentThemeObj.inputBorderColor" placeholder="请输入详细地址"
						:placeholder-style="`color:${currentThemeObj.placeholderColor}`" />
				</label-box>
			</item-box>
			<view class="u-margin-top-20">
				<item-box paddinglr="40">
					<label-box label="总店长" labelWidth="130">
						<view class="u-flex">
							<view v-if="userList.length" class="u-flex-1">
								<select-item v-model="form.dz" :disabled="isEdit&&isDz" :list="userList"
									@getSelect="getDz"></select-item>
							</view>
							<view class="u-flex-1 diy-input-box" v-else>
								<view style="color: #808080;">
									请先添加候选列表
								</view>
							</view>
							<view class="addList" v-if="!isDz" @click="showAddUserModel=true">
								<u-icon size="30" name="plus" :color="currentThemeObj.primary"></u-icon>
							</view>
						</view>
					</label-box>
					<label-box label="联系电话" labelWidth="130">
						<view class="u-flex-1 diy-input-box">
							<view style="overflow: hidden;" 　v-if="form.contactNumber">{{form.contactNumber}}</view>
							<view class="" v-else style="color: #808080;">
								请先选择店长
							</view>
						</view>
					</label-box>
				</item-box>
			</view>
			<view class="u-margin-top-20">
				<item-box>
					<view class="u-padding-left-40 u-padding-right-40">
						<label-box label="门店编号" labelWidth="130">
							<u-input v-model="form.storeNo" :clearable="false" border
								:borderColor="currentThemeObj.inputBorderColor" placeholder="请输入门店编号"
								:placeholder-style="`color:${currentThemeObj.placeholderColor}`" />
						</label-box>
						<label-box label="经营年数" labelWidth="130">
							<select-item v-model="form.businessYearLabel" :list="yearList" @getIds="getYearIds">
							</select-item>
						</label-box>
						<label-box label="营业状态" labelWidth="130">
							<select-item v-model="form.businessState" :list="businessStateList"></select-item>
						</label-box>
						<label-box label="营业时间" labelWidth="130">
							<view class="u-flex-1 u-flex">
								<view class="u-flex-1">
									<select-item v-model="form.dayTimeStart" mode="time" secondType="hourminute"></select-item>
								</view>
								<view class="u-padding-left-10 u-padding-right-10" style="color: #808080;">-</view>
								<view class="u-flex-1">
									<select-item v-model="form.dayTimeEnd" mode="time" secondType="hourminute"></select-item>
								</view>
							</view>
						</label-box>
					</view>
					<view class="store-tag-title u-font-32 box-title u-padding-top-48 u-padding-bottom-30 u-padding-left-40 u-padding-right-40">
						门店类型
					</view>
					<view>
						<u-row>
							<u-col span="4" v-for="(c,i) in tags" :key="i">
								<view class="u-flex u-row-center u-margin-bottom-40">
									<view class="u-position-relative">
										<view class="close u-flex u-row-center" @click="tagClick(i)">
											<u-icon name="close" custom-prefix="custom-icon" size="15" color="#333"></u-icon>
										</view>
										<item-btn height="64" width="194">{{c}}</item-btn>
									</view>
								</view>
							</u-col>
						</u-row>
					</view>
					<view class="u-padding-28 u-border-top">
						<item-btn @click="addTag" height="88" width="100%" type="plain">添加门店类型</item-btn>
					</view>
					<!-- <view>
						<text class="form-label">门店类型</text>
						<view class="u-flex u-margin-top-20 u-flex-wrap">
							<view class="u-margin-right-10 u-margin-top-10" v-for="(c,i) in tags" :key="i">
								<u-tag :text="c" closeable @close="tagClick(i)" shape="circle" close-color="#765CFE"
									bg-color="#161324" border-color="#423F4F" color="#D0D2F9" />
							</view>
							<view class="addTag" @click="addTag">
								<u-icon size="30" name="plus" color="#765CFE"></u-icon>
							</view>
						</view>
					</view> -->
				</item-box>
			</view>
			<fixed-team :btnText="option.id ? '修改门店' : '创建门店'" @btnClick="save" :loading="loading"></fixed-team>
		</view>
		<u-modal v-model="showAddUserModel" maskCloseAble title="新增店长" :show-confirm-button="false"
			:content-style="{'backgroundColor':'white'}"
			:title-style="{'backgroundColor':'white','color':'#333333','padding':'25rpx 0','borderBottom':'1rpx solid rgba(255,255,255,0.1)'}">
			<view>
				<view class="u-padding-left-30 u-padding-right-30">
					<label-box label="电话">
						<u-input v-model="phone" type="number" maxlength="11" :clearable="false" border
							:borderColor="currentThemeObj.inputBorderColor"
							 :placeholder-style="`color:${currentThemeObj.placeholderColor}`" placeholder="请输入电话"  />
					</label-box>
					<view class="u-padding-bottom-34 u-padding-top-46">
						<item-btn @click="search" width="100%" height="88">搜索</item-btn>
					</view>
				</view>
				<view class="u-flex u-padding-20 u-border-top" v-if="searchUser">
					<item-image :type="'1'" :img="searchUser.avatar" :size="80" />
					<view class="u-margin-left-12 text-order-time u-font-20 u-flex-1">
						<view class="u-margin-bottom-10">昵称：{{searchUser.nickname}}</view>
						<view class="u-margin-bottom-10">电话：{{searchUser.phone}}</view>
					</view>
					<view>
						<item-btn  @click="addSearch(searchUser)" height="54" width="150"><text class="u-font-24">添加</text></item-btn>
					</view>
					<!-- <view @click="addSearch(searchUser)" class="btn-style modal-add">添加 </view> -->
				</view>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import selectCityMixins from '@/mixins/selectMixins.js'
	import uploader from '@/components/upload/upload.vue'
	import {
		getDetail,
		add,
		update
	} from '@/api/crud.js'
	import {
		formatLocation
	} from '@/utils/index.js'
	import dayjs from 'dayjs'
	import amap from '@/utils/amap-wx.130'
	export default {
		mixins: [selectCityMixins],
		components: {
			uploader
		},
		computed: {
			title() {
				return this.option.id ? '编辑门店' : '创建门店'
			},
			tags() {
				const str = this.form && this.form.storeType || ''
				return str.split(',').filter(val => val) || []
			},
			isEdit() {
				return !!this.option.id
			}
		},
		data() {
			return {
				option: {},
				form: {
					dayTimeEnd: '',
					dayTimeStart: '',
					businessState: ''
				},
				uploadFlag: true,
				apiModule: 'shopApi',
				apiType: 'systemStore',
				yearList: [],
				userList: [],
				phone: "",
				showAddUserModel: false,
				time: '2020-02-20 ',
				searchUser: '',
				businessStateList: [{
					label: '营业',
					value: '营业'
				}, {
					label: '非营业',
					value: '非营业'
				}],
				uploadShow: false,
				loading: false,
				isDz: false,
				isStoreDetail: true,
				amapPlugin:null,
				chooseAddressLoading:false
			};
		},
		async onLoad(option) {
			this.option = option;
			this.amapPlugin = new amap.AMapWX({
				key: 'd4e796cdedd6a14b84e9de811795d1e5'  //该key 是在高德中申请的微信小程序key
			});
			if (option.id) {
				await getDetail(this.option, this.apiType, this.apiModule, 'getDetails').then(res => {
					this.form = res;
					if (res.dzUser && res.dzUser.length) {
						const dzUser = res.dzUser.map(this.setDzUserList);
						const firstDz = dzUser.find(val => val.value === res.dzUid)
						if (firstDz) { //如果有店长
							this.form.dz = firstDz.label;
							this.getDz([firstDz])
						}
						this.isDz = !!res.dzUid
					}
					this.getPersonList() //方法判断 没有店长列表的情况 有店长列表的情况 新建的情况
					this.form.dayTimeEnd = dayjs(this.form.dayTimeEnd).format("HH:mm");
					this.form.dayTimeStart = dayjs(this.form.dayTimeStart).format("HH:mm");
					if (res.cityPath) this.$set(this.form, 'cityAddress', this.cityPathFormat(res.cityPath))
					this.uploadShow = true
				})
			} else {
				this.getPersonList() //获取店长列表
				this.uploadShow = true
			}
			//获取经营年数
			this.$store.dispatch('getClassify').then(res => {
				const {
					children
				} = res.find(val => val.label == '经营年数') || {}
				this.yearList = children.map(val => {
					val.value = val.id;
					return val;
				}) || [];
				const year = this.yearList.find(val => val.id == this.form.businessYear);
				year && this.$set(this.form, 'businessYearLabel', year.cateName)
			})
			uni.$on('setTag', res => {
				this.$set(this.form, 'storeType', res)
			})
		},
		onUnload() {
			uni.$off('setTag')
		},
		methods: {
			getPersonList() {
				//获取店长人选
				if (this.form.dzUser && this.form.dzUser.length) {
					this.userList = this.form.dzUser.map(this.setDzUserList);
					return false;
				}
				getDetail({
					ownerUid: this.loginForm.uid
				}, 'storeOwnerUserRelation', this.apiModule, 'list').then(res => {
					this.userList = res.map(this.setDzUserList);
				})
			},
			setDzUserList({
				nickname,
				wxId,
				phone,
				clerkUid,
				id,
				uid
			}) {
				return {
					label: nickname,
					value: clerkUid || uid,
					extra: {
						wxId,
						contactNumber: phone
					}
				}
			},
			//上传的图片
			getImgStr(str) {
				this.form.sliderImage = str;
			},
			//监听上传图片
			getUpload(flag) {
				this.uploadFlag = flag;
			},
			//选择门店地址
			chooseAddress() {
				if(this.chooseAddressLoading){
					this.$u.toast('别点这么快')
					return false;
				}
				uni.chooseLocation({
					type: 'gcj02',
					success: (res) => {
						// this.form = {
						// 	...this.form,
						// 	latitude,
						// 	longitude
						// }; //选中的数据赋值给form
						const {address,latitude,longitude} = res;
						this.amapPlugin.getRegeo({
							location:`${longitude},${latitude}`,
							type: 'gcj02', //map 组件使用的经纬度是国测局坐标， type 为 gcj02
							success:(getRegeo)=> {
								const address = formatLocation(getRegeo);
								console.log(getRegeo,address)
								const cityPath = `${address.REGION_PROVINCE}-${address.REGION_COUNTRY}-${address.REGION_CITY}`
								const selectCityObj = {
									cityName:address.REGION_CITY,
									cityPath,
									cityId:0,
									latitude,
									longitude,
									cityAddress:cityPath,
									address:address.ADDRESS
								}
								this.form = {...this.form,...selectCityObj}; //选中的数据赋值给form
							}
						})
					},
					fail: res => {
						if (res.errMsg === 'chooseLocation:fail auth deny') this.$u.toast('您已拒绝授权，请打开设置允许')
					},
					complete:_=> {
						this.chooseAddressLoading = false;
					}
				})
			},
			getDz(obj) {
				const item = obj[0];
				this.form = {
					...this.form,
					...item.extra,
					dzUid: item.value
				}
			},
			//输入手机号码查询用户
			search() {
				if (!this.phone) {
					this.$u.toast('请输入手机号')
					return false
				}
				getDetail({
					phone: this.phone
				}, 'user', this.apiModule, 'findUserByPhoneInClerk').then(res => {
					if (!res) {
						this.$u.toast('该用户不可被添加')
						return false;
					}
					this.searchUser = res;
				})
			},
			//获取经营年数id
			getYearIds(item) {
				this.$set(this.form, 'businessYear', item)
			},
			//添加
			addSearch(item) {
				add({
					"clerkUid": item.uid,
					ownerUid: this.loginForm.uid
				}, 'storeOwnerUserRelation', this.apiModule).then(res => {
					this.$u.toast('添加成功')
					this.getPersonList()
					//重置
					this.showAddUserModel = false;
					this.phone = '';
					this.searchUser = ''
				})
			},
			save() {
				if (this.loading) {
					this.$u.toast('点太快了')
					return false
				}
				const {
					name,
					cityName,
					latitude,
					address,
					businessYear,
					businessState,
					dayTimeStart,
					dayTimeEnd,
					storeType,
					storeNo,
					sliderImage
				} = this.form;
				if (!name) {
					this.$u.toast('请填写门店名称')
					return false;
				}
				if (!cityName) {
					this.$u.toast('请选择所在城市')
					return false;
				}
				if (!latitude) {
					this.$u.toast('请设置地址经纬度')
					return false;
				}
				if (!address) {
					this.$u.toast('请设置详细地址')
					return false;
				}
				if (!businessYear) {
					this.$u.toast('请选择经营年数')
					return false;
				}
				if (!businessState) {
					this.$u.toast('请选择营业状态')
					return false;
				}
				if (!dayTimeStart) {
					this.$u.toast('请选择开始营业时间')
					return false;
				}
				if (!dayTimeEnd) {
					this.$u.toast('请选择结束营业时间')
					return false;
				}
				if (!storeType) {
					this.$u.toast('请选择门店类型')
					return false;
				}
				if (!storeNo) {
					this.$u.toast('请填写门店编号')
					return false;
				}
				if (!sliderImage) {
					this.$u.toast('请填写门店图片')
					return false;
				}
				const form = {
					...this.form
				};
				this.loading = true;
				form.dayTimeStart = this.time + form.dayTimeStart+':00'
				form.dayTimeEnd = this.time + form.dayTimeEnd+':00'
				const fn = this.isEdit ? update : add;
				fn(form, this.apiType, this.apiModule).then(res => {
					this.routeBack('操作成功');
					setTimeout(() => {
						this.loading = false
					}, 1500)
				}).catch(() => this.loading = false)
			},
			addTag() {
				this.$u.route({
					url: '/pagesA/storeTag/storeTag',
					params: {
						storeType: this.form.storeType
					}
				})
			},
			tagClick(index) {
				const val = this.tags[index];
				const storeType = this.form.storeType.split(',').filter(item => item != val).join(',')
				this.$set(this.form, 'storeType', storeType)
			}
		},
	}
</script>

<style lang="scss" scoped>
	.save-btn {
		padding: 100rpx 0;
	}

	.form-label {
		width: 210rpx;
		color: white;
		font-size: 32rpx;
	}

	.btn-style {
		width: 260rpx;
		line-height: 70rpx;
		text-align: center;
		margin: 0 auto;
		height: 70rpx;
		font-size: 26rpx;
		border-radius: 50rpx;
		background-color: #765CFE;
		color: white;
	}

	.tips {
		color: #fefefe;
	}

	.diy-input-box {
		padding: 0px 10px;
		border: 1px solid var(--line-color);
		text-align: left;
		overflow: hidden;
		white-space: nowrap;
		min-height: 64rpx;
		line-height: 64rpx;
		box-sizing: border-box;
		color: #333333;
		border-radius: 8rpx;
	}

	.addList {
		width: 74rpx;
		height: 64rpx;
		border: 1rpx solid var(--line-color);
		border-radius: 8rpx;
		text-align: center;
		line-height: 64rpx;
		box-sizing: border-box;
		margin-left: 10rpx;
	}

	.addTag {
		width: 126rpx;
		height: 52rpx;
		border: 1rpx solid #423F4F;
		border-radius: 100rpx;
		text-align: center;
		line-height: 48rpx;
		box-sizing: border-box;
		margin-right: 10rpx;
		margin-top: 10rpx;
		background-color: #161324;
	}

	.modal-add.btn-style {
		width: 150rpx;
		color: white;
		height: 54rpx;
		line-height: 54rpx;
		font-size: 24rpx;
	}

	.icon-view {
		padding-left: 15rpx;
		// border-left: 1rpx solid #423F4F;
	}
	
	.close{
		position: absolute;
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background-color: var(--background-second-color);
		top: -14rpx;
		right: -14rpx;
	}
</style>
